$(document).ready(function() {
	var searchBox = $("#search-box"),
		selected = {"entity": [], "value": []},
		results = {"entity": [], "value": []},
		workspaces = {
			"value": $("#value-workspace"),
			"entity": $("#entity-workspace"),
			"entity-group": $("#entity-group-workspace")
		},
		list = $("<ul/>").appendTo($("#workspace"));
	
	function requestData(type) {
		var d = $.Deferred();
		
		return $.getJSON("/" + type + "/",
			{q: searchBox.val()}, function(resData) {
				results[type] = resData.data;
			}).done(d.resolve);
	}
	
	// schedule, course, person
	
	searchBox.autocomplete({
		source: function(req, resp) {
			$.when(requestData("entity"), requestData("value"))
				.done(function() {
					resp(results);
				});
		},
		select: function(e, ui) {
			var item = ui.item,
				t = type(item),
				fullType = actualType(item),
				listItem = $("<li/>").appendTo(list),
				inject = null;
			
			if (fullType == "person") {
				inject = $("<img/>", {
					alt: (isValue(item) ? item.value : item.attr.name) + " inurl:uoit.ca"
				}).addClass("person-photo").googleImage();
			}
			
			var complete = Templater.render.widget(fullType, item, null, inject)
				.hide().appendTo(listItem);
			
			selected[t].push(item);
			searchBox.val("");
			
			return false;
		}
	});
	
	$("body").bind("operatorchanged", function(e) {
		console.log(e.op);
	});
	
	searchBox.bind("webkitspeechchange", function() {
		searchBox.autocomplete("search", $(this).value);
	});
	
	$("#resolve-entities").click(function() {
		var cons = $.map(selected["value"], function(itm, idx) {
			return {
				entity: itm.entity,
				attr: itm.attr,
				value: itm.value,
				op: "or"
			}
		});
		
		$.ajax("/entity/", {
			type: "POST",
			contentType: "application/json",
			data: JSON.stringify({ constraints: cons, topk: "3" }),
			dataType: "json",
			success: function(data) {
				var listItem = $("<li/>").appendTo(list);
				
				$.each(data.data, function(idx, itm) {
					Templater.render.widget(actualType(itm), itm, listItem);
				});
			}
		});
	});
	
	searchBox.focus();
})
